import router from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router'

// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  const whiteList = ['/login', '/404']
  // 开启进度条
  nProgress.start()
  // 如果有token
  if (store.getters.token) {
    if (to.path === '/login') {
      // 如果已经登录完了用户通过地址跳转到登录页，则进行拦截并跳转到首页
      next('/')
      nProgress.done()
    } else {
      // 有token且不是跳转到登录页
      if (!store.getters.userId) {
        // 如果没有用户信息，则进行获取用户信息
        const { roles } = await store.dispatch('user/getUserInfo')
        // 筛选后的路由
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        // 添加动态路由到信息表
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        store.commit('user/setRoutes', filterRoutes)
        next(to.path)
      } else {
        next()// 放行
      }
    }
  } else {
    // 没有token
    // 判断是否在白名单内
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

// 后置路由守卫
router.afterEach(() => {
  nProgress.done()
})
